package cn.wolfcode.shiro.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author simple
 */
@Component
public class UserRealm extends AuthorizingRealm {
    private static Map<String, String> userData = new HashMap<>(2);
    private static Map<String, List<String>> permissionData = new HashMap<>(2);

    static {
        userData.put("zhangsan", "666");
        userData.put("lisi", "888");
        //zhangsan拥有员工页面和部门页面的访问权限
        List<String> p1 = new ArrayList<>();
        p1.add("employee:page");
        p1.add("department:page");
        permissionData.put("zhangsan", p1);
        //lisi只拥有部门页面的访问全新
        List<String> p2 = new ArrayList<>();
        p2.add("department:page");
        permissionData.put("lisi", p2);
    }

    @Override
    public String getName() {
        return "UserRealm";
    }

    /**
     * 授权
     *
     * @param principals PrincipalCollection
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登陆的信息
        String userName = (String) principals.getPrimaryPrincipal();
        //获取登陆用户的权限信息
        List<String> perms = permissionData.get(userName);
        //创建授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //关联用户的权限信息
        info.addStringPermissions(perms);
        return info;
    }

    /**
     * 认证
     *
     * @param token AuthenticationToken
     * @return AuthenticationInfo
     * @throws AuthenticationException AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = userData.get(username);
        if (password == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
